<?php

namespace App\Service;

use Predis\Client;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

/**
 * chat.php
 * Send any incoming messages to all connected clients (except sender)
 */
class Mychat implements MessageComponentInterface {
    protected $clients;

    /**
     * @var Client
     */
    protected $redis;


    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    /**
     * @param Client $redis
     */
    public function setRedis(Client $redis): void
    {
        $this->redis = $redis;
    }



    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        foreach ($this->clients as $client) {
//            if ($from != $client) {
                $client->send("we receive your msg:".$msg);
//            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        $conn->close();
    }

    /**
     * @return \SplObjectStorage
     */
    public function getClients(): \SplObjectStorage
    {
        return $this->clients;
    }


}